ip config<template>
  <div class="login">
      <el-card class="box-card">
          <div slot="header" class="clearfix">
              <span>文件访问控制系统</span>
          </div>
          <el-tabs
              v-model="currentIndex"
              stretch
              @tab-click="handleTabsClick"
          >
              <el-tab-pane label="登录" name="login">
                  <el-form
                      :model="loginForm"
                      :rules="rules"
                      status-icon
                      ref="loginForm"
                  >
                      <el-form-item
                          label="用户名"
                          label-width="80px"
                          prop="username"
                      >
                          <el-input
                              type="text"
                              v-model="loginForm.username"
                          />
                      </el-form-item>
                      <el-form-item
                          label="密码"
                          label-width="80px"
                          prop="password"
                      >
                          <el-input
                              type="password"
                              v-model="loginForm.password"
                          />
                      </el-form-item>
                      <el-form-item>
                          <el-button
                              type="primary"
                              @click="submitForm('loginForm')"
                              >提交</el-button
                          >
                      </el-form-item>
                  </el-form>
              </el-tab-pane>
              <el-tab-pane label="注册" name="register">
                <el-form
                    :model="registerForm"
                    :rules="rules"
                    status-icon
                    ref="registerForm"
                >
                      <el-form-item
                          label="用户名"
                          label-width="80px"
                          prop="username"
                      >
                          <el-input
                              type="text"
                              v-model="registerForm.username"
                          />
                      </el-form-item>

                      <el-form-item
                          label="密码"
                          label-width="80px"
                          prop="password"
                      >
                          <el-input
                              type="password"
                              v-model="registerForm.password"
                          />
                      </el-form-item>
                      <el-form-item
                          label="确认密码"
                          label-width="80px"
                          prop="configurePassword"
                      >
                          <el-input
                              type="password"
                              v-model="registerForm.configurePassword"
                          />
                      </el-form-item>
                      <el-form-item>
                          <el-button
                              type="primary"
                              @click="submitForm('registerForm')"
                              >提交</el-button
                          >
                      </el-form-item>
                        <div class="download-link">
                            <el-button @click="downloadToolPackage">工具包下载</el-button>
                        </div>
                  </el-form>
              </el-tab-pane>
          </el-tabs>
      </el-card>
 </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
      var validateUserName = (rule, value, callback) => {
          if (value === "") {
              callback(new Error("请输入用户名"));
          } else if (value.length < 4) {
              callback(new Error("长度不够"));
          } else {
              callback();
          }
      };
      var validatePassWord = (rule, value, callback) => {
          if (value === "") {
              callback(new Error("请输入密码"));
          } else {
              callback();
          }
      };
      var validateConfigurePassword = (rule, value, callback) => {
          if (value === "") {
              callback(new Error("请输入密码"));
          } else if (value !== this.registerForm.password) {
              callback(new Error("两次输入密码不一致!"));
          } else {
              callback();
          }
      };
      return {
          currentIndex: "login",
          loginForm: {
              username: "",
              password: "",
          },
          registerForm: {
              username: "",
              password: "",
              configurePassword: "",
          },
          activeTab: "login",
          rules: {
              username: [
                  {
                      validator: validateUserName,
                      trigger: "blur",
                  },
              ],
              password: [
                  {
                      validator: validatePassWord,
                      trigger: "blur",
                  },
              ],
              configurePassword: [
                  {
                      validator: validateConfigurePassword,
                      trigger: "blur",
                  },
              ],
          },
      };
  },
  methods: {
      submitForm(formName) {
          this.$refs[formName].validate(async (valid) => {
              if (valid) {
                  if (this.activeTab === "login") {
                      try {
                            const response = await axios.post('http://192.168.124.128:8081/api/login', this.loginForm);
                            const token = response.data.token;
                            localStorage.setItem('token', token);
                            const username = this.loginForm.username;
                            localStorage.setItem('username', username);
                            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
                            this.$router.push("/");
                        } catch (error) {
                            console.error('Error during login:', error);
                            let message = '登录失败';
                            if (error.response && error.response.data && error.response.data.error) {
                                message += ': ' + error.response.data.error;
                            }
                            alert(message);
                        }
                  } else if (this.activeTab === "register") {
                       try {
                            const response = await axios.post('http://192.168.124.128:8081/api/register', {
                                username: this.registerForm.username,
                                publicKey: this.registerForm.publicKey,
                                password: this.registerForm.password,
                            });
                            alert('注册成功!请前往登录');
                        } catch (error) {
                            console.error('Error during registration:', error);
                            if (error.response && error.response.data) {
                                alert('注册过程中发生错误: ' + error.response.data.error);
                            } else {
                                alert('注册过程中发生未知错误!');
                            }
                        }
                    }
              } else {
                  return;
              }
          });
      },
      handleTabsClick(tab) {
          this.activeTab = tab.name;
      },
      async downloadToolPackage() {
            try {
                const response = await axios({
                    url: 'http://192.168.124.128:8081/api/downloadtool', 
                    method: 'GET',
                    responseType: 'blob', 
                });

                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'tool-package.zip');
                document.body.appendChild(link);
                link.click();
            } catch (error) {
                console.error('Download error:', error);
                alert('下载失败');
            }
        },
    },
};
</script>

<style scoped lang="less">
.login {
  width: 1200px;
  margin: 0 auto;
.box-card {
    width: 600px;
    margin: 100px auto;
}
.download-link {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;

    a {
        color: #3498db;
        text-decoration: underline;
        cursor: pointer;
        &:hover {
            color: #2980b9;
        }
    }
}
}
</style>